from flask import jsonify, Blueprint, make_response, g
import sys

from common import ApiResponse, Result
from flask_pydantic import validate
import logging
import json


from .service import Service
from .dantic import *

LOGGER = logging.getLogger(__name__)
chat2ai_blueprint = Blueprint("chat2ai", __name__)


# validate 方法是python的Decorator,当定义的方法被call的时候，decorator会先执行。
@chat2ai_blueprint.route("/", methods=["GET"])
@validate()
def test():
    """测试服务器端是否正常的接口，浏览器可以直接访问"""
    return make_response({"status": 200, "message": "hello"}, 200)


@chat2ai_blueprint.route("/chat", methods=["POST"])
@validate()
def chat(body: ParamChat):

    try:
        body.userId = g.userid
        body.isVipUser = g.isVip
    except Exception as e:
        LOGGER.error(e)
        return ApiResponse().needLogin().json()

    res: Result = Service().getChatReply(body)
    if res.isSucc():
        return ApiResponse().set_data(res.data).json()
    return ApiResponse().error(res.message).json()


@chat2ai_blueprint.route("/getTitle", methods=["POST"])
@validate()
def getTitle(body: ParamTitle):

    try:
        body.userId = g.userid
        body.isVipUser = g.isVip
    except Exception as e:
        LOGGER.error(e)
        return ApiResponse().needLogin().json()

    res: Result = Service().getTitle(body)
    if res.isSucc():
        return ApiResponse().set_data(res.data).json()
    return ApiResponse().error(res.message).json()


@chat2ai_blueprint.route("/getOutline", methods=["POST"])
@validate()
def getOutline(body: ParamOutline):
    try:

        body.userId = g.userid
        body.isVipUser = g.isVip
    except Exception as e:
        LOGGER.error(e)
        return ApiResponse().needLogin().json()

    res: Result = Service().getOutline(body)
    if res.isSucc():
        return ApiResponse().set_data(res.data).json()
    return ApiResponse().error(res.message).json()


@chat2ai_blueprint.route("/exportOutline", methods=["POST"])
@validate()
def exportOutline(body: ParamSelect4Content):

    try:
        body.userId = g.userid
        body.isVipUser = g.isVip
        if not g.isVip:
            return ApiResponse().error("仅vip会员可导出提纲word文档").json()
    except Exception as e:
        return ApiResponse().needLogin().json()

    res: Result = Service().exportOutline(body)
    if res.is_success():
        return ApiResponse().set_data(res.data).json()
    return ApiResponse().error(res.message).json()


@chat2ai_blueprint.route("/select4Content", methods=["POST"])
@validate()
def select4Content(body: ParamSelect4Content):

    try:
        body.userId = g.userid
        body.isVipUser = g.isVip
    except Exception as e:
        return ApiResponse().needLogin().json()

    res: Result = Service().select4Content(body)
    if res.is_success():
        return ApiResponse().set_data(res.data).json()
    return ApiResponse().error(res.message).json()


@chat2ai_blueprint.route("/stopGenerateAll", methods=["POST"])
@validate()
def stopGenerateAll(body: ParamThesisId):
    try:
        body.userId = g.userid
        body.isVipUser = g.isVip
    except Exception as e:
        return ApiResponse().needLogin().json()

    try:

        res: Result = Service().stopThesisGenerate(body)
        if res.isSucc():
            return ApiResponse().json()
        return ApiResponse().error(res.message).json()
    except Exception as e:
        LOGGER.exception(e)
        return ApiResponse().error(str(e)).json()


@chat2ai_blueprint.route("/generateAll", methods=["POST"])
@validate()
def pushGenerateTask(body: ParamThesisId):

    try:
        body.userId = g.userid
        body.isVipUser = g.isVip
        if not body.isVipUser:
            return (
                ApiResponse()
                .error("抱歉，当前时段服务器压力较大，仅VIP用户可使用此功能")
                .json()
            )
        thesisId = body.thesisId
        thesis = Service().getThesisById(thesisId)
        if thesis is None:
            LOGGER.error(f"id {thesisId} 未查询到论文")
            return ApiResponse().error("").json()

        if type(thesis.outline) is not dict:
            LOGGER.error(f"id {thesisId} 论文存储数据格式错误")
            return ApiResponse().error("论文存储数据格式错误").json()

        if thesis.uid != g.userid:
            LOGGER.error(
                f"thesis.uid = {thesis.uid},g.uid = {g.userid} 有人要访问别人的论文"
            )
            return ApiResponse().error("未查询到此论文").json()

        res: Result = Service().setThesisNeedGenerate(thesisId)
        if res.isSucc():
            return ApiResponse().json()
        return ApiResponse().error(res.message).json()
    except Exception as e:
        LOGGER.exception(e)
        return ApiResponse().error(str(e)).json()


@chat2ai_blueprint.route("/generateSingleParagraph", methods=["POST"])
@validate()
def generateSingleParagraph(body: ParamGenerateSingleParagraph):

    try:
        body.userId = g.userid
        body.isVipUser = g.isVip
    except Exception as e:
        return ApiResponse().needLogin().json()

    res: Result = Service().generateSingleParagraph(body)
    if res.is_success():
        return ApiResponse().json()
    return ApiResponse().error(res.message).json()


@chat2ai_blueprint.route("/generateDigest", methods=["POST"])
@validate()
def generateDigest(body: ParamThesisId):

    try:

        body.userId = g.userid
        body.isVipUser = g.isVip
    except Exception as e:
        return ApiResponse().needLogin().json()

    res: Result = Service().generateDigest(body)
    if not res.isSucc():
        return ApiResponse().error(res.message).json()
    res: Result = Service().generateDigestEnglish(body)
    if not res.isSucc():
        return ApiResponse().error(res.message).json()
    return ApiResponse().json()


@chat2ai_blueprint.route("/generateThanks", methods=["POST"])
@validate()
def generateThanks(body: ParamThesisId):

    try:

        body.userId = g.userid
        body.isVipUser = g.isVip
    except Exception as e:
        return ApiResponse().needLogin().json()

    res: Result = Service().generateThanks(body)
    if not res.isSucc():
        return ApiResponse().error(res.message).json()
    return ApiResponse().json()


@chat2ai_blueprint.route("/generateReference", methods=["POST"])
@validate()
def generateReference(body: ParamThesisId):

    try:

        body.userId = g.userid
        body.isVipUser = g.isVip
    except Exception as e:
        return ApiResponse().needLogin().json()

    res: Result = Service().generateReference(body)
    if not res.isSucc():
        return ApiResponse().error(res.message).json()
    return ApiResponse().json()
